import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_model/user/wallet_model_entity.dart';
import 'package:xvideos/hj_page/mine_business/mine_profit/mine_profit_page/bank_card_home_page.dart';
import 'package:xvideos/hj_utils/api_service/mine_service.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/loading/LoadingHelper.dart';

import '../../../alert_business/mine/vip_level_dialog.dart';
import '../../../hj_utils/global.dart';
import '../../../hj_utils/utils.dart';
import '../mine_profit/mine_profit_page/model/alipay_bank_list_model.dart';
import 'in_come_entity.dart';

class WithdrawalLogic extends GetxController with GetTickerProviderStateMixin {
  WithdrawalLogic get to => Get.find<WithdrawalLogic>();

  TextEditingController? moneyController;
  TextEditingController? accountController;
  FocusNode focusNode = FocusNode();
  bool isShowLoading = false;

  WalletModelEntity? userIncomeModel;
  WithdrawConfig? configData;
  TextEditingController? nameController;
  bool isLoading = true;

  int withdrawType = 1; // 0支付宝 1银行卡
  Channel? selectChannel;

  num handlingFee = 0; //手续费
  num actualAmount = 0; //实际到账金额
  AccountInfoModel? bankModel;
  int get minBankCardMoney {
    return (configData?.getBankCardChannel?.minMoney ?? 0) ~/ 100;
  }

  int get minUsdtMoney {
    return (configData?.getUsdtChannel?.minMoney ?? 0) ~/ 100;
  }

  @override
  void onInit() {
    super.onInit();
    moneyController = TextEditingController();
    nameController = TextEditingController();
    accountController = TextEditingController();
  }

  @override
  void onReady() {
    super.onReady();
    loadData(showLoading: true);
    globalStore.refreshWallet();
  }

  void changeWithdrawType(String payType) {
    // withdrawType = value;
    selectChannel = configData?.channels?.firstWhere((element) => element.payType == payType);
    withdrawType = configData?.channels?.indexWhere((e) => e.payType == selectChannel?.payType) ?? 0;
    update();
  }

  ///计算提现手续费、实际到账金额
  void calcWithdrawAmount(String withdrawAmount) {
    if (withdrawAmount.isEmpty) {
      handlingFee = 0;
      actualAmount = 0;
    } else {
      num withdrawAmoutNum = num.parse(withdrawAmount);
      int coinTax = configData?.coinTax ?? 0;
      if (coinTax == 0) {
        handlingFee = 0;
        actualAmount = withdrawAmoutNum;
      } else {
        double value = coinTax / 100.0;
        final res = (withdrawAmoutNum * double.parse(value.toStringAsFixed(2))).toStringAsFixed(2);
        handlingFee = double.parse(res).floor();
        actualAmount = withdrawAmoutNum - handlingFee;
      }
    }
    update(['money']);
  }

  @override
  void dispose() {
    super.dispose();
    nameController?.dispose();
    moneyController?.dispose();
    accountController?.dispose();
    focusNode.dispose();
  }

  Future<void> loadData({
    bool isRefresh = true,
    bool showLoading = false,
  }) async {
    //获取支付宝或者银行卡的费率
    _withdrawConfigReq();
  }

  ///提现配置请求
  void _withdrawConfigReq() async {
    final configData = await MineService.withdrawConfig();
    this.configData = configData;
    isLoading = false;
    selectChannel = configData?.channels?.firstWhereOrNull((element) => element.payType == 'bankcard');
    if (selectChannel == null) {
      selectChannel = configData?.channels?.firstWhereOrNull((element) => element.payType == 'usdt');
      if (selectChannel == null) {
        showToast('暂无可用提现通道');
        this.configData = null;
      }
    } else {
      withdrawType = configData?.channels?.indexWhere((e) => e.payType == selectChannel?.payType) ?? 0;
    }
    update();
  }

  ///提交提现
  void submitWithdraw() async {
    try {
      if (!globalStore.isRechargeVIP()) {
        showVipLevelDialog("您还不是VIP，无法使用提现功能");
        return;
      }

      if ("bankcard" == selectChannel?.payType) {
        //检验银行卡信息
        _commonWithdrawReq(true);
      } else if ("alipay" == selectChannel?.payType || "usdt" == selectChannel?.payType) {
        _commonWithdrawReq(false);
      }
    } catch (e) {
      showToast("提现错误:$e");
    }
  }

  ///公用提现方法
  void _commonWithdrawReq(bool isbankType) async {
    Channel channel = configData!.channels![withdrawType];
    String money = moneyController?.text.trim() ?? "";
    String accountDesc = accountController?.text.trim() ?? "";
    if (isbankType) {
      accountDesc = bankModel?.act ?? "";
    }
    if (money.isEmpty) {
      showToast("提现金额不能为空");
      return;
    }
    if (isbankType && bankModel == null) {
      showToast("请选择提现银行卡号");
      return;
    }
    if (!isbankType && accountDesc.isEmpty) {
      showToast("请输入钱包地址");
      return;
    }

    double incomeMoneyYuan = (userIncomeModel?.walletBalance() ?? 0) / 10;
    int withdrawMoneyYuan = int.parse(money);
    if (withdrawMoneyYuan > incomeMoneyYuan) {
      showToast("提现金额不能大于余额");
      return;
    }

    int minMoneyFen = configData?.channels![withdrawType].minMoney ?? 0;
    double minMoneyYuan = minMoneyFen / 100;
    if (withdrawMoneyYuan < minMoneyYuan) {
      showToast("单笔提现金额不小于$minMoneyYuan元");
      return;
    }
    int maxMoneyFen = configData?.channels![withdrawType].maxMoney ?? 0;
    double maxMoneyYuan = maxMoneyFen / 100;
    if (withdrawMoneyYuan > maxMoneyYuan) {
      showToast("单笔提现金额不大于$maxMoneyYuan元");
      return;
    }

    LoadingHelper.showLoading();

    String deviceId = await getDeviceOaid();
    String payType = channel.payType ?? "";
    //payType 提现方式，alipay，bankcard，usdt
    //money  提现金额
    //name 用户名
    //withdrawType 提现类型，0，代理提现； 1，金币提现
    //actName 交易账户持有人
    //act 交易账户
    //devID 设备id
    //productType 产品类型 0站群 1棋牌
    var result = await MineService.withdraw(
      payType,
      accountDesc,
      withdrawMoneyYuan * 100,
      globalStore.getMe()?.name ?? "",
      bankModel?.actName,
      deviceId,
      bankModel?.bankCode,
      1,
      0,
    );
    LoadingHelper.dismissLoading();
    if (result == true) {
      globalStore.refreshWallet(refresh: true);
      showToast("提现提交成功～");

      clearInputData();
    } else {
      showToast("提现失败～");
    }
  }

  void gotoBankList() async {
    var ret = await Get.to(
      BankCardHomePage(selectModel: bankModel),
      preventDuplicates: false,
    );
    if (ret is AccountInfoModel) {
      bankModel = ret;
      update();
    }
  }

  clearInputData() {
    nameController?.clear();
    accountController?.clear();
    moneyController?.clear();
  }
}
